package com.zhudoo.zhilian.util;

import jodd.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加解密工具
 *
 * @author mac
 */
public class EncryptUtil {

    private static final String TOKEN_KEY = "wangniantokenkey";

    /**
     * 根据token加密密文token
     *
     * @param token
     * @return
     */
    public static String encrypt(String token) {
        return encrypt(token, TOKEN_KEY);
    }

    /**
     * 根据token解密密文token
     *
     * @param encryptToken
     * @return
     */
    public static String decrypt(String encryptToken) {
        return decrypt(encryptToken, TOKEN_KEY);
    }


    /**
     * 加密
     *
     * @param content
     * @param password
     * @return
     */
    public static String encrypt(String content, String password) {
        try {
            byte[] raw = password.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(content.getBytes());
            return Base64.encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @param password
     * @return
     */
    public static String decrypt(String content, String password) {
        try {
            byte[] raw = password.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = Base64.decode(content);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                return null;
            }
        } catch (Exception ex) {
            return null;
        }

    }


    public static void main(String[] args) {
        System.out.println(EncryptUtil.decrypt("IzL/l0BYjId89pp3dowM5w=="));
        System.out.println(EncryptUtil.encrypt("1111"));
    }

}
